from fastapi import APIRouter, Query,UploadFile
from tortoise.expressions import Q

from app.settings.config import settings
from app.controllers.mini.layers import mini_layers_controller
from app.models import CustomerUser
from app.schemas.base import Success, SuccessExtra,Fail
from app.schemas.mini import *
from app.utils.upload import upload_image,upload_file
mini_layers_router = APIRouter()
model_name = "圈层"


@mini_layers_router.get("/list", summary=f"查看{model_name}列表")
async def do_settings_list(
        page: int = Query(1, description="页码"),
        page_size: int = Query(10, description="每页数量"),
        title: str = Query(None, description=f"{model_name}标题"),
        user_name: str = Query(None, description=f"用户姓名"),
):
    search_user_ids = []
    q = Q()
    if user_name:
        search_users = await CustomerUser.filter(name__contains=user_name).values("id")
        search_user_ids = {orders['id'] for orders in search_users}  # 获取所有的 user_id
    if title:
        q &= Q(name__contains=title)
    if search_user_ids:
        q &= Q(user_id__in=search_user_ids)
    total, data = await mini_layers_controller.do_list(page=page, page_size=page_size, search=q)
    user_ids = {layers['user_id'] for layers in data}  # 获取所有的 user_id
    users = await CustomerUser.filter(id__in=user_ids)
    users_dict = {user.id: user.name for user in users}
    for layer in data:
        layer['user_name'] = users_dict.get(layer['user_id'], "已删除用户")
        layer['status_name'] = settings.APPOINTMENT_STATUS[layer['status']]
    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)

@mini_layers_router.get("/get", summary=f"查看{model_name}")
async def do_settings_get(
        data_id: int = Query(..., description="ID"),
):
    data = await mini_layers_controller.do_detail(data_id=data_id)
    return Success(data=data)


@mini_layers_router.post("/update", summary=f"更新{model_name}")
async def do_settings_update(
        data_in: MiniLayersUpdate,
):
    await mini_layers_controller.do_update(obj_in=data_in)
    return Success(msg="更新成功")

@mini_layers_router.delete("/delete", summary=f"删除{model_name}")
async def do_settings_delete(
        data_id: int = Query(..., description="ID"),
):
    await mini_layers_controller.do_delete(data_id=data_id)
    return Success(msg="删除成功")

